package com.fh.wanandroid.ui.main;

import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.fh.wanandroid.R;
import com.fh.wanandroid.app.Constants;
import com.fh.wanandroid.base.BaseActivity;
import com.fh.wanandroid.base.BaseFragment;
import com.fh.wanandroid.base.BasePresenter;
import com.fh.wanandroid.ui.knowledge.fragment.KnowledgeFragment;
import com.fh.wanandroid.ui.login.activity.LoginActivity;
import com.fh.wanandroid.ui.mainpager.MainPagerFragment;
import com.fh.wanandroid.ui.navigation.fragment.NavigationFragment;
import com.fh.wanandroid.ui.project.fragment.ProjectFragment;
import com.fh.wanandroid.ui.register.RegisterActivity;
import com.fh.wanandroid.ui.wx.fragment.WXArticleFragment;
import com.fh.wanandroid.utils.BottomNavigationViewHelper;
import com.fh.wanandroid.utils.StatusBarUtil;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {


    @BindView(R.id.common_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.fragment_group)
    FrameLayout fragmentGroup;
    @BindView(R.id.bottom_navigation_view)
    BottomNavigationView mBottomNavigationView;
    @BindView(R.id.nav_view)
    NavigationView mNavigationView;
    @BindView(R.id.common_toolbar_title_tv)
    TextView mTitleTv;
    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.main_floating_action_btn)
    FloatingActionButton mFloatingActionButton;



    private TextView mUsTv;

    private int mLastFgIndex;
    private ArrayList<BaseFragment> mFragments;
    private MainPagerFragment mainPagerFragment;
    private KnowledgeFragment knowledgeFragment;
    private WXArticleFragment mWxArticleFragment;
    private NavigationFragment navigationFragment;
    private ProjectFragment projectFragment;

    int page;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }


    @Override
    public BasePresenter getmPresenter() {
        return null;
    }

    @Override
    public void presenterSetView() {

    }

    @Override
    public void initView() {

        //设置toolbar
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.setDisplayShowTitleEnabled(false);
        mTitleTv.setText(getString(R.string.home_pager));
        StatusBarUtil.setStatusColor(getWindow(), ContextCompat.getColor(this, R.color.main_status_bar_blue), 1f);


        page = Constants.TYPE_MAIN_PAGER;
//        mToolbar.setNavigationOnClickListener(v -> onBackPressedSupport());
        initNavigationView();
        initDrawerLayout();
        initBottomNavigationView();

    }

    @Override
    public void initData() {

        initPager(true, 0);


    }

    private void initPager(boolean isRecreate, int position) {

        mFragments = new ArrayList<>();
        mainPagerFragment = MainPagerFragment.getInstance(isRecreate, null);

        mFragments.add(mainPagerFragment);
        initFragments();
//        init();
        switchFragment(position);
    }

//    void onBackPressedSupport(){
//
//    }

    void initFragments() {

        knowledgeFragment = KnowledgeFragment.getInstance(false, null);

        mWxArticleFragment = WXArticleFragment.getInstance("1","2");

        navigationFragment = NavigationFragment.getInstance(false,"1");

        projectFragment =   ProjectFragment.getInstance("1",1);

        mFragments.add(knowledgeFragment);

        mFragments.add(mWxArticleFragment);

        mFragments.add(navigationFragment);

        mFragments.add(projectFragment);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_activity_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_usage:
//                if (usageDialogFragment == null) {
//                    usageDialogFragment = new UsageDialogFragment();
//                }
//                if (!isDestroyed() && usageDialogFragment.isAdded()) {
//                    usageDialogFragment.dismiss();
//                }
//                usageDialogFragment.show(getSupportFragmentManager(), "UsageDialogFragment");
                break;
            case R.id.action_search:
//                if (searchDialogFragment == null) {
//                    searchDialogFragment = new SearchDialogFragment();
//                }
//                if (!isDestroyed() && searchDialogFragment.isAdded()) {
//                    searchDialogFragment.dismiss();
//                }
//                searchDialogFragment.show(getSupportFragmentManager(), "SearchDialogFragment");
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {

    }


    @OnClick({R.id.main_floating_action_btn})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_floating_action_btn:
                jumpToTheTop();
                break;
            default:
                break;
        }
    }


    public void initNavigationView() {


        mUsTv = mNavigationView.getHeaderView(0).findViewById(R.id.nav_header_login_tv);


        //当没有登录的时候，显示登录的按钮
        if(Constants.userName.equals("")){

            showLoginView();

        }else{

            showLogoutView();

        }


        mNavigationView.getMenu().findItem(R.id.nav_item_wan_android)
                .setOnMenuItemClickListener(item -> {

                    startMainPager();

                    return true;
                });


        mNavigationView.getMenu().findItem(R.id.nav_item_my_collect)
                .setOnMenuItemClickListener(item -> {
//                    if (mPresenter.getLoginStatus()) {
//                        startCollectFragment();
//                        return true;
//                    } else {
//                        startActivity(new Intent(this, LoginActivity.class));
//                        CommonUtils.showMessage(this, getString(R.string.login_tint));
//                        return true;
//                    }

                    return true;
                });

    }


    public void initDrawerLayout() {


        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mDrawerLayout, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                //获取mDrawerLayout中的第一个子布局，也就是布局中的RelativeLayout
                //获取抽屉的view
                View mContent = mDrawerLayout.getChildAt(0);
                float scale = 1 - slideOffset;
                float endScale = 0.8f + scale * 0.2f;
                float startScale = 1 - 0.3f * scale;

                //设置左边菜单滑动后的占据屏幕大小
                drawerView.setScaleX(startScale);
                drawerView.setScaleY(startScale);
                //设置菜单透明度
                drawerView.setAlpha(0.6f + 0.4f * (1 - scale));

                //设置内容界面水平和垂直方向偏转量
                //在滑动时内容界面的宽度为 屏幕宽度减去菜单界面所占宽度
                mContent.setTranslationX(drawerView.getMeasuredWidth() * (1 - scale));
                //设置内容界面操作无效（比如有button就会点击无效）
                mContent.invalidate();
                //设置右边菜单滑动后的占据屏幕大小
                mContent.setScaleX(endScale);
                mContent.setScaleY(endScale);
            }
        };
        toggle.syncState();
        mDrawerLayout.addDrawerListener(toggle);

    }


    public void initBottomNavigationView() {

        BottomNavigationViewHelper.disableShiftMode(mBottomNavigationView);
        mBottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.tab_main_pager:
                    loadPager(getString(R.string.home_pager), 0,
                            mainPagerFragment, Constants.TYPE_MAIN_PAGER);
                    break;
                case R.id.tab_knowledge_hierarchy:
                    loadPager("知识体系", 1,
                            knowledgeFragment, Constants.TYPE_KNOWLEDGE);
                    break;
                case R.id.tab_wx_article:
                    loadPager("公众号", 2,
                            mWxArticleFragment, Constants.TYPE_WX_ARTICLE);
                    break;
                case R.id.tab_navigation:
                    loadPager("公众号", 3,
                            navigationFragment, Constants.TYPE_NAVIGATION);
                    break;
                case R.id.tab_project:
//                    loadPager(getString(R.string.project), 4,
//                            mProjectFragment, Constants.TYPE_PROJECT);
                    loadPager("项目", 4,
                            projectFragment, Constants.TYPE_PROJECT);
                    break;
                default:
                    break;
            }
            return true;
        });
    }


    private void loadPager(String title, int position, BaseFragment mFragment, int pagerType) {
        mTitleTv.setText(title);
        switchFragment(position);
//        mPresenter.setCurrentPage(pagerType);
        page = pagerType;
    }


    /**
     * 切换fragment
     *
     * @param position 要显示的fragment的下标
     */
    private void switchFragment(int position) {

        if (position >= Constants.TYPE_COLLECT) {
            mFloatingActionButton.hide();
            mBottomNavigationView.setVisibility(View.INVISIBLE);
        } else {
//            mFloatingActionButton.setVisibility(View.VISIBLE);
            mFloatingActionButton.show();
            mBottomNavigationView.setVisibility(View.VISIBLE);
        }

        if (position >= mFragments.size()) {
            return;
        }


        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment targetFg = mFragments.get(position);
        Fragment lastFg = mFragments.get(mLastFgIndex);
        mLastFgIndex = position;
        ft.hide(lastFg);
        if (!targetFg.isAdded()) {
            getSupportFragmentManager().beginTransaction().remove(targetFg).commitAllowingStateLoss();
            ft.add(R.id.fragment_group, targetFg);
        }
        ft.show(targetFg);
        ft.commitAllowingStateLoss();

    }

    private void jumpToTheTop() {

        switch (page) {
            case Constants.TYPE_MAIN_PAGER:
                if (mainPagerFragment != null) {
                    mainPagerFragment.jumpToTheTop();
                }
                break;
            case Constants.TYPE_KNOWLEDGE:
                if (knowledgeFragment != null) {
                    knowledgeFragment.jumpToTheTop();
                }
                break;
//            case Constants.TYPE_WX_ARTICLE:
//                if (mWxArticleFragment != null) {
//                    mWxArticleFragment.jumpToTheTop();
//                }
//            case Constants.TYPE_NAVIGATION:
//                if (mNavigationFragment != null) {
//                    mNavigationFragment.jumpToTheTop();
//                }
//                break;
//            case Constants.TYPE_PROJECT:
//                if (mProjectFragment != null) {
//                    mProjectFragment.jumpToTheTop();
//                }
//                break;
            default:
                break;
        }
    }


    private void startMainPager() {
        mBottomNavigationView.setVisibility(View.VISIBLE);
        mBottomNavigationView.setSelectedItemId(R.id.tab_main_pager);
        mDrawerLayout.closeDrawers();
    }


    private void showLogoutView(){

        mUsTv.setText(Constants.userName);

        mUsTv.setOnClickListener(null);


        mNavigationView.getMenu().findItem(R.id.nav_item_logout).setVisible(true);

    }


    private void  showLoginView(){

        mUsTv.setText("登录");

        mUsTv.setOnClickListener(v -> startActivity(new Intent(this, LoginActivity.class)));

        mNavigationView.getMenu().findItem(R.id.nav_item_logout).setVisible(false);


    }

}
